package com.wang.websocket.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@ServerEndpoint("/api/{id}")
public class WebSocketServer {

    //记录当前连接数
    private static final ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<>();
    private String id;

    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id){
        this.id = id;
        webSocketMap.put(id, session);
        log.info("【websocket消息】有新的连接，总数为:"+webSocketMap.size());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketMap.remove(this.id);
        log.info("【websocket消息】连接断开，总数为:"+webSocketMap.size());
    }

    /**
     * 收到客户端消息后调用的方法
     **/
    @OnMessage
    public void onMessage(String message) throws IOException {
        log.info("收到客户端消息：{}", message);
        sendAllMessage(message);
    }

    /**
     * 发生异常调用方法
     */
    @OnError
    public void onError(Throwable error) {
        log.error("用户错误,原因:"+error.getMessage());
        error.printStackTrace();
    }

    public void sendAllMessage(String message) {
        log.info("【websocket消息】广播消息:"+message);
        webSocketMap.forEach((id, session) -> {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

}
